package com.common.handler;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import com.common.configuration.SystemDefaultJWTConfiguration;
import com.common.enums.ApiResult;
import com.common.pojo.Token;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description: 系统默认身份验证成功的处理形式
 * @Date: 2025/6/6 14:59
 */
public class SystemDefaultAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired(required = false)
    private SystemDefaultJWTConfiguration systemDefaultJWTConfiguration = new SystemDefaultJWTConfiguration();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        JWT jwt = JWT.create();
        DateTime expiresAt = DateUtil.offset(DateUtil.date(), systemDefaultJWTConfiguration.getDateField(), systemDefaultJWTConfiguration.getOffset());
        jwt.setExpiresAt(expiresAt);
        jwt.setPayload("userId", authentication.getPrincipal());
        jwt.setKey(systemDefaultJWTConfiguration.getKey().getBytes());
        String token = jwt.sign();
        BearerToken bearerToken = new BearerToken();
        bearerToken.setTokenType("Bearer");
        bearerToken.setAccessToken(token);
        bearerToken.setExpiredAt(expiresAt.getTime());
        ApiResult responseResult = ApiResult.success(bearerToken);
        PrintWriter writer = response.getWriter();
        writer.write(JSONUtil.parseObj(responseResult).toStringPretty());
        writer.flush();
        writer.close();
    }
     class BearerToken extends Token{
        private String accessToken;//访问令牌
        private Long expiredAt;//过期时间

         public String getAccessToken() {
             return accessToken;
         }

         public void setAccessToken(String accessToken) {
             this.accessToken = accessToken;
         }

         public Long getExpiredAt() {
             return expiredAt;
         }

         public void setExpiredAt(Long expiredAt) {
             this.expiredAt = expiredAt;
         }
     }
}
